package day16;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

/**
 * 需求：
 * 获取某一个字符串中字母出现的次数
 * 希望打印格式如下：a(1)c(3)d(5)
 * 什么时候使用Map集合呢？
 * 当数据之间存在映射关系时，就要先想到使用Map集合
 * @author wangbiao
 *
 */
public class MapStringTest {

	public static void main(String[] args) {
		String str = "acbere6erawd";
		System.out.println(charCount(str));
	}
	
	public static String charCount(String str) {
		if (null == str) {
			return null;
		}
		char[] chs = str.toCharArray();
		Map<Character, Integer> map = new TreeMap<Character,Integer>();
		for (int i = 0,len = chs.length; i < len; i++) {
			if (!(chs[i] >= 'a' && chs[i] <= 'z' || chs[i] >= 'A' && chs[i] <= 'Z')) {
				continue;
			}
			Integer value = map.get(chs[i]);
			if (null == value) {
				map.put(chs[i], 1);
			} else {
				value += 1;
				map.put(chs[i], value);
			}
		}
		Set<Entry<Character, Integer>> entrySet = map.entrySet();
		StringBuilder builder = new StringBuilder();
		for (Iterator<Entry<Character,Integer>> iterator = entrySet.iterator(); iterator.hasNext();) {
			Entry<Character, Integer> entry = iterator.next();
			Character key = entry.getKey();
			Integer value = entry.getValue();
			builder.append(key+"("+value+")");
		}
		return builder.toString();
	}
	
}
